package com.mission.schedule.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mission.schedule.R;
import com.mission.schedule.activity.MainActivity;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.qd606.NoteTitleDetailBean;
import com.mission.schedule.widget.SwipeLinearLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liwei on 2017/4/28.
 */

public class NoteExpandListAdapter extends BaseAdapter {

    Context context;
    LayoutInflater layoutInflater;

    Handler handler;

    List<NoteTitleDetailBean.TDelListBean> tdellist = new ArrayList<>();

    int colors[] = {R.color.white, R.color.color_m_1, R.color.color_m_2, R.color.color_m_3, R.color.color_m_4, R.color.color_m_5};

    public NoteExpandListAdapter(Context context, Handler handler,
                                 ArrayList<NoteTitleDetailBean.TDelListBean> tdellist) {
        this.context = context;
        this.handler = handler;
        this.tdellist = tdellist;
        layoutInflater = LayoutInflater.from(context);
    }

    public void copyOneNoteTitle(String titleid, String userid) {
        NoteTitleDetailBean.TDelListBean tDelListBean = App.getDBcApplication().getOneNoteTitlesData(userid, titleid, false);
        tdellist.add(0, tDelListBean);
        notifyDataSetChanged();
    }

    public void topNoteTitle(int ositioin) {
        NoteTitleDetailBean.TDelListBean listBeen = tdellist.get(ositioin);
        tdellist.remove(ositioin);
        tdellist.add(0, listBeen);
        notifyDataSetChanged();
    }

    public void updateOpenstate(int positioin, int openstate) {
        tdellist.get(positioin).openState = openstate;
        notifyDataSetChanged();
    }

    public void updateOpenstate(int positioin,String remark5, String remark6) {
        tdellist.get(positioin).remark5 = remark5;
        tdellist.get(positioin).remark6 = remark6;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return tdellist.size();
    }

    @Override
    public Object getItem(int position) {
        return tdellist.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ChildViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ChildViewHolder();
            convertView = layoutInflater.inflate(R.layout.adapter_qdlist, parent, false);
            viewHolder.swipeLayout = convertView.findViewById(R.id.swipeLayout);
            viewHolder.emptylayout = convertView.findViewById(R.id.emptylayout);
            viewHolder.qdll = convertView.findViewById(R.id.qdll);
            viewHolder.more = convertView.findViewById(R.id.more);
            viewHolder.time = convertView.findViewById(R.id.time);
            viewHolder.title = convertView.findViewById(R.id.title);
            viewHolder.tv_delete = convertView.findViewById(R.id.tv_delete);
            viewHolder.yuandian = convertView.findViewById(R.id.yuandian);
            viewHolder.share = convertView.findViewById(R.id.share);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ChildViewHolder) convertView.getTag();
        }
        swipeLinearLayouts.add(viewHolder.swipeLayout);
        viewHolder.swipeLayout.setOnSwipeListener(new SwipeLinearLayout.OnSwipeListener() {
            @Override
            public void onDirectionJudged(SwipeLinearLayout thisSll, boolean isHorizontal) {
                if (false == isHorizontal) {
                    for (SwipeLinearLayout sll : swipeLinearLayouts) {
                        if (null == sll) {
                            continue;
                        }
                        sll.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK);
                    }
                } else {
                    ssllayout = position;
                    for (SwipeLinearLayout sll : swipeLinearLayouts) {
                        if (null == sll) {
                            continue;
                        }
                        if (!sll.equals(thisSll)) {
                            //划开一个sll， 其他收缩
                            sll.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK);
                        }
                    }
                }
            }
        });
        viewHolder.qdll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                send(2, position);
                updateShouDaoYuandian(position);
                viewHolder.swipeLayout.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK);
            }
        });
        viewHolder.qdll.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                send(6, position);
                viewHolder.swipeLayout.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK);
                return true;
            }
        });
        viewHolder.more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                send(6, position);
                viewHolder.swipeLayout.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK);
            }
        });
        if (tdellist.get(position).other1.equals("1")) {
            viewHolder.yuandian.setVisibility(View.VISIBLE);
        } else {
            viewHolder.yuandian.setVisibility(View.GONE);
        }
        viewHolder.tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewHolder.swipeLayout.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK);
                deletelist(position);
            }
        });

        if (tdellist.size() > 0) {
            if (tdellist.get(position).titleId != null) {
                viewHolder.swipeLayout.setVisibility(View.VISIBLE);
                viewHolder.emptylayout.setVisibility(View.GONE);


//                if (tdellist.get(position).openState == 1) {
//                    viewHolder.share.setText("公开");
//                    viewHolder.share.setVisibility(View.VISIBLE);
//                } else {
//                    viewHolder.share.setVisibility(View.GONE);
//                    viewHolder.share.setText("");
//                }
                viewHolder.title.setText("");
                int num = App.getDBcApplication().getTitleNoteDetailData(tdellist.get(position).uid + "", tdellist.get(position).titleId, false).size();
                String titlestr;
                if (tdellist.get(position).titles.equals("")) {
                    titlestr = App.getDBcApplication().getNoteTitleDetailContent(tdellist.get(position).uid + "", tdellist.get(position).titleId);
                    if (titlestr.isEmpty()) {
                        titlestr = "无标题";
                    } else {
                        if (titlestr.length() > 16) {
                            titlestr = titlestr.substring(0, 16);
                        }
                    }

                } else {
                    titlestr = tdellist.get(position).titles;
                    if (titlestr.length() > 16) {
                        titlestr = titlestr.substring(0, 16);
                    }
                }

                String title_new;

                if (tdellist.get(position).styles == 0) {
                    int tick = App.getDBcApplication().getNoteDetailEndstateNums(tdellist.get(position).titleId, tdellist.get(position).uid + "");
                    if (num == 0) {
                        title_new = "";
                    } else {
                        title_new = "(" + tick + "/" + num + ")";
                    }
                } else if (tdellist.get(position).styles == 4) {
                    int tick1 = App.getDBcApplication().getNoteDetailEndstateNums(tdellist.get(position).titleId, tdellist.get(position).uid + "", 1);
                    int tick2 = App.getDBcApplication().getNoteDetailEndstateNums(tdellist.get(position).titleId, tdellist.get(position).uid + "", 2);
                    if (num == 0) {
                        title_new = "";
                    } else {
                        title_new = "(" + tick1 + "/" + tick2 + "/" + num + ")";
                    }
                } else {
                    if (num == 0) {
                        title_new = "";
                    } else {
                        title_new = "(" + num + ")";
                    }
                }
                if (tdellist.get(position).remark3 != null && (tdellist.get(position).remark3.equals("1")
                        || tdellist.get(position).remark3.equals("2"))) {
                    if (!titlestr.isEmpty()) {
                        titlestr = "#" + titlestr;
                    }
                }
                SpannableString builder = new SpannableString(titlestr);
                builder.setSpan(new ForegroundColorSpan(Color.BLACK), 0, titlestr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                if (titlestr.indexOf("#") == 0) {
                    builder.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.title0)), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                viewHolder.title.append(builder);


                String pname = "@" + tdellist.get(position).pname;

//                if (tdellist.get(position).remark3.equals("1")
//                        || tdellist.get(position).remark3.equals("2")) {
//                    //收藏清单
//                    SpannableString builder1 = new SpannableString(pname);
//                    builder1.setSpan(new ForegroundColorSpan(Color.parseColor("#aaaaaa")), 0, pname.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//                    viewHolder.title.append(builder1);
//                }
                SpannableString builder2 = new SpannableString(title_new);
                ForegroundColorSpan span = new ForegroundColorSpan(Color.parseColor("#aaaaaa"));
                builder2.setSpan(span, 0, title_new.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                viewHolder.title.append(builder2);
                if (tdellist.get(position).createTime != null) {
                    String shares = "";
                    String lz = " @";
                    if (!tdellist.get(position).nums.equals("0") && !tdellist.get(position).nums.isEmpty()) {
                        shares = " 已分享";
                    }
                    if (tdellist.get(position).remark3 != null && (tdellist.get(position).remark3.equals("1")
                            || tdellist.get(position).remark3.equals("2"))) {
                        shares = "";
                        lz = " 来自: " + pname;
                    }
                    viewHolder.time.setText(tdellist.get(position).createTime.
                            substring(5, tdellist.get(position).createTime.length() - 3).replace('T', ' ') + shares);
                }

                String remark6 = tdellist.get(position).remark6;
                if (remark6 == "" || remark6 == null) {
                    remark6 = "0";
                }
                int color = Integer.valueOf(remark6);
                if (color > 0) {
                    SpannableString builder3 = new SpannableString(viewHolder.title.getText().toString());
                    builder3.setSpan(new BackgroundColorSpan(context.getResources().getColor(colors[color])), 0, viewHolder.title.getText().toString().length(),
                            Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                    if (color > 2) {
                        builder3.setSpan(new ForegroundColorSpan(Color.WHITE), 0, viewHolder.title.getText().toString().length(),
                                Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                    }
                    viewHolder.title.setText(builder3);
                    viewHolder.title.setLineSpacing(1f, 1f);
                }

            } else {
                viewHolder.swipeLayout.setVisibility(View.GONE);
                viewHolder.emptylayout.setVisibility(View.VISIBLE);
            }
        }
        return convertView;
    }

    public void deletelist(int position) {
        App.getDBcApplication().deleteNoteTitleData(tdellist.get(position).titleId, tdellist.get(position).uid + "", false);
        tdellist.remove(position);
        send(5, position);
        notifyDataSetChanged();
    }


    public void updateShouDaoYuandian(int g) {
        tdellist.get(g).setRemark2("0");
        notifyDataSetChanged();
        App.getDBcApplication().updateNoteTitleother1(tdellist.get(g).uid, tdellist.get(g).titleId);
        MainActivity.instance.updateNoteTitleNoReadNums();
        send(5, g);
    }

    int ssllayout = -1;

    private int showStringLength(String str) {
        String regex = "[\u4e00-\u9fff]";

        if (str.length() > 12) {
            int count = (" " + str.substring(0, 12) + " ").split(regex).length - 1;
            int onC = 12 - count;
            int length = 12 + onC % 2;
            if (str.length() > length) {
                return length;
            } else {
                return str.length();
            }
        } else {
            return str.length();
        }
    }

    // 判断一个字符是否是中文
    public static boolean isChinese(char c) {
        return c >= 0x4E00 && c <= 0x9FA5;// 根据字节码判断
    }

    // 判断一个字符串是否含有中文
    public static boolean isChinese(String str) {
        if (str == null) return false;
        for (char c : str.toCharArray()) {
            if (isChinese(c)) return true;// 有一个中文字符就返回
        }
        return false;
    }

    List<SwipeLinearLayout> swipeLinearLayouts = new ArrayList<>();

    class ChildViewHolder {
        SwipeLinearLayout swipeLayout;
        LinearLayout more, emptylayout, qdll;
        TextView title, time, tv_delete, yuandian, share;
    }

    private void send(int what, int position) {
        Message message = new Message();
        message.what = what;
        message.arg1 = position;
        handler.sendMessage(message);
    }

    //设置双#号包裹的文字颜色
    private void setcolor(String content, TextView editText) {
        SpannableStringBuilder builder = new SpannableStringBuilder(content);
        if (content.length() > 1) {
            List<Integer> integerList = new ArrayList<>();
            int index = 0;
            int count = hit(content, "#");
            if (count > 1) {
                if (count % 2 == 0) {
                    for (int i = 0; i < count; i++) {
                        if (i == 0) {
                            index = content.indexOf("#");
                        } else {
                            index = content.indexOf("#", index + 1);
                        }
                        integerList.add(index);
                    }
                    for (int i = 0; i < integerList.size(); i++) {
                        if (i > 0) {
                            if (i % 2 != 0) {
                                ForegroundColorSpan span = new ForegroundColorSpan(Color.BLACK);
                                builder.setSpan(span, integerList.get(i - 1), integerList.get(i) + 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                            }
                        }
                    }
                    editText.setText(builder);
                } else {
                    for (int i = 0; i < count - 1; i++) {
                        if (i == 0) {
                            index = content.indexOf("#");
                        } else {
                            index = content.indexOf("#", index + 1);
                        }
                        integerList.add(index);

                    }
                    for (int i = 0; i < integerList.size(); i++) {
                        if (i > 0) {
                            if (i % 2 != 0) {
                                ForegroundColorSpan span = new ForegroundColorSpan(Color.BLACK);
                                builder.setSpan(span, integerList.get(i - 1), integerList.get(i) + 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                            }
                        }
                    }
                    editText.setText(builder);
                }
            } else {
                editText.setText(builder);
            }
        } else {
            editText.setText(builder);
        }
    }

    public int hit(String a, String b) {
        if (a.length() < b.length()) {
            return 0;
        }
        char[] a_t = a.toCharArray();
        int count = 0;

        for (int i = 0; i < a.length(); i++) {
            StringBuffer buffer = new StringBuffer();
            for (int j = 0; j < b.length(); j++) {
                buffer.append(a_t[i + j]);
            }
            if (buffer.toString().equals(b)) {
                count++;
            }
        }

        return count;
    }
}
